import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../color.dart';

/// @author: pengboboer
/// @createDate: 2022/1/10
class LoadingUtils {
  static void showLoading(BuildContext context,
      {String? content,
      bool isCanBack = false,
      ValueChanged<ValueNotifier<String>>? onControllerCallback}) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return _LoadingWidget(
              content: content,
              isCanBack: isCanBack,
              onControllerCallback: onControllerCallback);
        });
  }
}

class _LoadingWidget extends StatefulWidget {
  final String? content;
  final bool isCanBack;
  final ValueChanged<ValueNotifier<String>>? onControllerCallback;

  const _LoadingWidget(
      {Key? key,
      this.content,
      this.onControllerCallback,
      this.isCanBack = true})
      : super(key: key);

  @override
  _LoadingWidgetState createState() => _LoadingWidgetState();
}

class _LoadingWidgetState extends State<_LoadingWidget> {
  final ValueNotifier<String> _notifier = ValueNotifier("");

  @override
  void initState() {
    super.initState();
    _notifier.value = widget.content ?? "";
    widget.onControllerCallback?.call(_notifier);
  }

  @override
  void dispose() {
    super.dispose();
    _notifier.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return widget.isCanBack;
      },
      child: Material(
        color: Colors.transparent,
        child: Container(
          alignment: Alignment.center,
          width: 375.w,
          height: 812.w,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                valueColor:
                    AlwaysStoppedAnimation<Color>(ColorManager.colorD93C3A),
              ),
              ValueListenableBuilder<String>(
                  valueListenable: _notifier,
                  builder: (context, content, child) {
                    return Visibility(
                      visible: content != "",
                      child: Padding(
                        padding: EdgeInsets.only(top: 15.w),
                        child: Text(
                          content,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: ColorManager.colorF87E75.withOpacity(0.95),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    );
                  }),
            ],
          ),
        ),
      ),
    );
  }
}
